// import { Chart } from "chart.js";
Chart.plugins.register({
  afterDatasetsDraw: function (chartInstance, easing) {
    // To only draw at the end of animation, check for easing === 1
    var ctx = chartInstance.chart.ctx;
    // console.debug("Chart Instance: ", chartInstance);
    if (!chartInstance.options.alwaysLable || chartInstance.config.type !== "pie") return;
    chartInstance.data.datasets.forEach(function (dataset, i) {
      var meta = chartInstance.getDatasetMeta(i);
      var validAccalc = dataset.data.reduce((acc, cur, index) => meta.data[index]["hidden"] ? acc : acc + cur, 0);
      if (!meta.hidden) {
        let numToHidden = 0;
        meta.data.forEach(function (element, index) {
          // Draw the text in black, with the specified font
          ctx.fillStyle = 'rgb(255, 255, 255)';
          // console.debug("Ele: ", element)
          if (element.hidden) return;
          var fontSize = 12;
          var fontStyle = 'normal';
          var fontFamily = 'Microsoft Yahei';
          ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
          // Just naively convert to string for now
          var dataNumber = (dataset.data[index] / validAccalc * 100);
          if (dataNumber < 8) return;
          var dataString = dataNumber.toFixed(0).toString() + "%";

          // Make sure alignment settings are correct
          ctx.textAlign = 'center';
          ctx.textBaseline = 'middle';
          // var position = element.tooltipPosition();
          var position = getOuterAreaLabelPoint.call(element, fontSize);
          ctx.fillText(dataString, position.x, position.y);
        });
      }
    });
  }
});

function getOuterAreaLabelPoint(textOffset) {
  var vm = this._view;
  var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2),
    rangeFromCentre = vm.outerRadius / 5 * 3;
    // rangeFromCentre = vm.outerRadius - (textOffset || 20) + Math.abs(Math.sin(Math.PI / 2 + centreAngle)) * (textOffset || 20) * 0.8;
  return {
    x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
    y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  };
};